package com.jcnet.bizaia.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.json.JSONObject;

import android.R.integer;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jcnet.bizaia.App;
import com.jcnet.bizaia.DiscussDetialActivity;
import com.jcnet.bizaia.FavouriteActivity;
import com.jcnet.bizaia.R;
import com.jcnet.bizaia.VodDetailActivity;
import com.jcnet.bizaia.R.id;
import com.jcnet.bizaia.adapter.FavouriteVodAdapter;
import com.jcnet.bizaia.adapter.MainInfoAdapter;
import com.jcnet.bizaia.bean.AllInfoBeanRequest;
import com.jcnet.bizaia.bean.DiscussSearchInfoBean;
import com.jcnet.bizaia.bean.FavouriteVodBean;
import com.jcnet.bizaia.bean.MainInfoBean;
import com.jcnet.bizaia.tools.JCTools;
import com.jcnet.bizaia.tools.Toolkit;
import com.jcnet.bizaia.view.HeadViewPageView;
import com.jcnet.bizaia.view.ProgressWheel;
import com.jcnet.bizaia.xstream.ACache;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;


@SuppressLint("ValidFragment")
public class FavouriteVodFragment extends SherlockFragment implements OnItemClickListener {

	private List<FavouriteVodBean> mainInfoBeans;

	private List<FavouriteVodBean>tempInfoBeans;

	private PullToRefreshListView listView;

	private ListView simpleListView ;

	private View bottomView;  //底部加载更多按钮


	//private View emptyView;     //数据为空

	private View noNetWorkView;  //没有网络\


	private View firstLodingView;  //没有网络\

	private FavouriteVodAdapter infoAdapter;

	private int nowPageSize = 1;

	private int category =0;

	private ACache aCache;

	private String HTTP_REQUEST =  App.HTTP_PATH+"favo_showFavouritesList.action?";

	//private RequestParams params;
	
	private int allPapeSize;
	
	private BroadcastReceiver broadcastReceiver;
	
	public static final String DISCUSSIONINFOFRAGMENT_STRING = "DISCUSSIONINFOFRAGMENT_STRING" ;
	
	
	private boolean isInit  = true;
	
	private AsyncHttpClient asyncHttpClient;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		asyncHttpClient = new AsyncHttpClient();

		aCache = ACache.get(getActivity());

		//params = new RequestParams();

		View view = View.inflate(getActivity(), R.layout.comm_list_onrefresh,null);

		bottomView = View.inflate(getActivity(), R.layout.comm_foot_view, null);

		firstLodingView = View.inflate(getActivity(), R.layout.init_locad_view, null);

		listView = (PullToRefreshListView)view.findViewById(R.id.commListViewWitheRefresh);

		//emptyView = View.inflate(getActivity(), R.layout.list_empty_no_data, null);
		
		noNetWorkView = View.inflate(getActivity(), R.layout.list_no_network, null);

		initListView();
		System.out.println("onCreateView__________________");
		
		
		broadcastReceiver = new BroadcastReceiver() {
			
			@Override
			public void onReceive(Context context, Intent intent) {
				// TODO Auto-generated method stub
				boolean  isEdit = intent.getExtras().getBoolean("isEdit");
				infoAdapter.isEdit = isEdit;
				infoAdapter.notifyDataSetChanged();
			}
		};
		getActivity().registerReceiver(broadcastReceiver, new IntentFilter(FavouriteActivity.EDIT_FAVOURIT));
		
		return view;
	}
	
	
	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		// TODO Auto-generated method stub
		super.setUserVisibleHint(isVisibleToUser);
		System.out.println("isVisibleToUser__________________");
		
		if(isVisibleToUser&&isInit){
			sendHttp(nowPageSize);
			isInit = false;
		}
	}

	
	public static FavouriteVodFragment newInstance(int category) {
		FavouriteVodFragment fragment = new FavouriteVodFragment();
		fragment.category = category;
		return fragment;
	}


	public FavouriteVodFragment() {
		super();
		// TODO Auto-generated constructor stub
	}





	public FavouriteVodFragment(int category) {
		super();
		this.category = category;
	}


	
	

	private void initListView() {
		// TODO Auto-generated method stub

		mainInfoBeans = new ArrayList<FavouriteVodBean>();

		tempInfoBeans = new ArrayList<FavouriteVodBean>();


		infoAdapter = new FavouriteVodAdapter(getActivity(), mainInfoBeans);


		listView.setOnItemClickListener(this);


		listView.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
				// TODO Auto-generated method stub   下拉刷新

				
				if(Toolkit.isAvaliable(getActivity())){
					if(mainInfoBeans!=null){
						mainInfoBeans.clear();
					}
					nowPageSize = 1;
					sendHttp(nowPageSize);
				}else{
					
					Toast.makeText(getActivity(), getString(R.string.noNetWork), 0).show();
					refreshView.onRefreshComplete();
					
				}
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
				// TODO Auto-generated method stub

			}
		});

		listView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

			@Override
			public void onLastItemVisible() {
				// TODO Auto-generated method stub
				
				System.out.println("??????????????");
				System.out.println("nowPageSize"+nowPageSize);
				System.out.println("allPapeSize"+allPapeSize);
				
				if(nowPageSize==allPapeSize){
					bottomView.setVisibility(View.GONE);   //到达底部没有更多数据
					Toast.makeText(getActivity(), getString(R.string.noData), 0).show();
				}else{
					bottomView.setVisibility(View.VISIBLE);  //到达底部还有更多数据
					nowPageSize = nowPageSize+1;
					sendHttp(nowPageSize);
				}

			}
		});

		simpleListView = listView.getRefreshableView();
		simpleListView.setAdapter(infoAdapter);
		simpleListView.setOnItemClickListener(this);
		simpleListView.setEmptyView(firstLodingView);
		simpleListView.addFooterView(bottomView);

	}

	public void sendHttp(int page){
		
		
		/**
		 * @param
		 *  参数名称	参数类型	说明
			languageNum	int	语言种类：1：中文2：英文3：日文
			title	string	讲座标题
			disidNum	int	地区id
			iidNum	int	行业id检索 （默认全部时赋值-1）
			holddateNum	date	时间日期检索（搜索全部时赋值null/-1等均可）
			crmoneyNum	int	费用检索 （搜索全部时赋值-1）
			useridNum	int	用户id(用户未登录赋值-1)
			pageNum	int	当前第几页（默认第一页）
			pageSizeNum	int	当前分页显示条数（默认20条）
		 */
		
		final RequestParams params = new RequestParams();
		params.put("languageNum", App.localeCode+"");
		params.put("useridNum", JCTools.getUserID(getActivity())+"");     //用户id 需要动态
		params.put("pageNum", page+"");
		params.put("ftypeNum", category+"");
		//params.put("pageSizeNum",20);
		

		if(Toolkit.isAvaliable(getActivity())){

			asyncHttpClient.post(HTTP_REQUEST,params ,new AsyncHttpResponseHandler(){

				@Override
				public void onStart() {
					// TODO Auto-generated method stub
					super.onStart();
					
				}

				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					// TODO Auto-generated method stub\

					super.onSuccess(arg0, arg1, arg2);

					if(new String(arg2)!=null){

						aCache.put(HTTP_REQUEST+params, new String(arg2),App.CACHE_TIME_DAY);
						setListData(new String(arg2));
					}
					
					
				}


				@Override
				public void onFinish() {
					// TODO Auto-generated method stub
					super.onFinish();
					if(listView.isRefreshing()){
						listView.onRefreshComplete();
					}
					bottomView.setVisibility(View.GONE);
				}

				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2,
						Throwable arg3) {
					// TODO Auto-generated method stub
					Toast.makeText(getActivity(), getString(R.string.serverError), 0).show();
					super.onFailure(arg0, arg1, arg2, arg3);
				}
			});
		}else{
			if(listView.isRefreshing()){
				listView.onRefreshComplete();
			}

			simpleListView.setEmptyView(noNetWorkView);


			firstLodingView.setVisibility(View.GONE);

			String requestString = aCache.getAsJSONObject(HTTP_REQUEST+params).toString();
			
			if(requestString!=null){
				
				setListData(requestString);
			}
			
			
			Toast.makeText(getActivity(), getString(R.string.noNetWork), 1).show();

		}
	}
	
	
	private void setListData(String arg2){
		

		
		String requestString = arg2;

		AllRequestBean requestBeanRequest = new AllRequestBean();

		//System.out.println("byte:"+new String(arg2));

		if(requestString!=null){
			
			
			requestBeanRequest = new Gson().fromJson(requestString, new TypeToken<AllRequestBean>(){}.getType());

			
			allPapeSize = requestBeanRequest.getPagsum();
			
			if(requestBeanRequest.getState()==200){

				firstLodingView.setVisibility(View.GONE);
				
				tempInfoBeans = null;
				
				tempInfoBeans = requestBeanRequest.getObjlistJson();
				
				if(!tempInfoBeans.isEmpty()||tempInfoBeans!=null){
					
					if(tempInfoBeans.isEmpty()||mainInfoBeans.size()<20){   //当本页的

						bottomView.setVisibility(View.GONE);

					}
					
					if(!tempInfoBeans.isEmpty()){

						mainInfoBeans.addAll(tempInfoBeans);

						infoAdapter.count = mainInfoBeans.size();

						infoAdapter.notifyDataSetChanged();
					}
				}


				//如果得到的内容总数为空的话显示没有数据的页面,同时隐藏foot界面
				if(mainInfoBeans.isEmpty()){
					//simpleListView.setEmptyView(emptyView);
					bottomView.setVisibility(View.GONE);
				}


			}

			listView.onRefreshComplete();
		}

	}
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		String source = "http://devimages.apple.com/iphone/samples/bipbop/gear4/prog_index.m3u8";
		//Intent intent = new Intent(getActivity(), VideoViewPlayingActivity.class);
		Intent intent = new Intent(getActivity(), VodDetailActivity.class);
		
		intent.setData(Uri.parse(source));
		
		startActivity(intent);	
	}

	
	class AllRequestBean{
		private int state;
		private String message;
		private int pagsum;
		private List<FavouriteVodBean>objlistJson;
		public int getState() {
			return state;
		}
		public void setState(int state) {
			this.state = state;
		}
		public String getMessage() {
			return message;
		}
		public void setMessage(String message) {
			this.message = message;
		}
		public int getPagsum() {
			return pagsum;
		}
		public void setPagsum(int pagsum) {
			this.pagsum = pagsum;
		}
		public List<FavouriteVodBean> getObjlistJson() {
			return objlistJson;
		}
		public void setObjlistJson(List<FavouriteVodBean> objlistJson) {
			this.objlistJson = objlistJson;
		}
		
		
		
		
	}

}
